﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataCashLib;

public partial class Subscription : System.Web.UI.Page
{
    protected string dataCashClient = "99571100";
    protected string dataCashPassword = "nAwc3Yqt";
    protected string dataCashUrl = "https://testserver.datacash.com/Transaction";
    private UserSub userSub = new UserSub();
    private static Subs subscription = new Subs();
    private string AuthCode = "";
    private string Reference;
    private static int orderId;
    protected void Page_Load(object sender, EventArgs e)
    {
        userSub = SubsciptionAccess.GetUserSubscription(User.Identity.Name);
        if (userSub.idSubscription == 0)
        {
            if (!IsPostBack)
            {
                gvSubs.DataSource = SubsciptionAccess.GetAllSubscriptions();
                gvSubs.DataBind();
            }
        }
        else
        {
            Response.Redirect("HomePage.aspx");
        }

    }

    protected void gvSubs_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtAmount.Text = ((Label)gvSubs.SelectedRow.Cells[2].FindControl("lblCena")).Text;
        subscription.cost = Convert.ToInt32(txtAmount.Text);  
        subscription.idSubscription = Convert.ToInt32(((HiddenField)gvSubs.SelectedRow.Cells[2].FindControl("hfId")).Value);
    }

    protected void btnSubmitPreRequest_Click(object sender, EventArgs e)
    {
        orderId=SubsciptionAccess.CreateOrder(subscription.idSubscription, User.Identity.Name);
        int orderIdPadded =Convert.ToInt32(orderId.ToString().PadLeft(7, '0').PadLeft(8, '2'));
        SendPreRequest(orderIdPadded);
    }

    protected DataCashRequest GeneratePreRequest(int orderId2)
    {
        // Construct pre request
        DataCashRequest request = new DataCashRequest();
        request.Transaction.TxnDetails.MerchantReference = orderId2.ToString();
        request.Authentication.Client = dataCashClient;
        request.Authentication.Password = dataCashPassword;
        request.Transaction.TxnDetails.Amount.Amount = subscription.cost.ToString();
        request.Transaction.TxnDetails.Amount.Currency = "GBP";
        request.Transaction.CardTxn.Method = "pre";
        request.Transaction.CardTxn.Card.CardNumber = txtCardNumber.Text;
        request.Transaction.CardTxn.Card.ExpiryDate = txtExpiryDate.Text;
        return request;
    }

    protected DataCashRequest GenerateFulfillRequest(int orderId2)
    {
        DataCashRequest request = new DataCashRequest();
        request.Authentication.Client = dataCashClient;
        request.Authentication.Password = dataCashPassword;
        request.Transaction.TxnDetails.MerchantReference = orderId2.ToString();
        request.Transaction.HistoricTxn.Method = "fulfill";
        request.Transaction.HistoricTxn.AuthCode = AuthCode;

        try
        {
            request.Transaction.HistoricTxn.Reference = Reference;
        }
        catch
        {
            lblProba.Text = "Неуспешно плаќање.";
        }
        return request;
    }

    protected void SendPreRequest(int orderId2)
    {
        DataCashResponse response;
        DataCashRequest request = GeneratePreRequest(orderId2);
        response = request.GetResponse(dataCashUrl);

        try
        {
            AuthCode = response.CardTxn.AuthCode;
            Reference = response.DatacashReference;
        }
        catch (Exception ex)
        {
            AuthCode = string.Empty;
        }

        if (AuthCode != null)
        {
            SendFullRequest(orderId2);
        }
        else
        {
            lblProba.Text = "Неуспешно плаќање.";
            SubsciptionAccess.CancelOrder(orderId);
            ClearFields();
        }
    }

    protected void SendFullRequest(int orderId2)
    {
        DataCashResponse response;
        DataCashRequest request = GenerateFulfillRequest(orderId2);
        response = request.GetResponse(dataCashUrl);
        if (Convert.ToInt32(response.Status) == 1)
        {
            pnlSUb.Visible = false;
            lblProba.Text = "Успешна наплата";
            btnContinue.Visible = true;
            SubsciptionAccess.CompleteOrder(orderId);
        }
    }
    protected void ClearFields()
    {
        txtCardNumber.Text = "";
        txtExpiryDate.Text = "";
        txtAmount.Text = "";
    }

    protected void btnContinue_Click(object sender, EventArgs e)
    {
        Response.Redirect("ProfilePage.aspx");
    }
}
